package com.bilifuture.statemachine.transition;

import com.bilifuture.statemachine.action.Action;
import com.bilifuture.statemachine.interceptor.StateMachineInterceptor;
import com.bilifuture.statemachine.machine.StateMachineContext;
import com.bilifuture.statemachine.message.Response;
import lombok.Data;

import java.util.List;

/**
 * @author bilifuture
 * @description:
 * @date 2022-02-23
 */
@Data
public class Transition {
    
    /**
     * 事件
     */
    private String event;
    
    /**
     * 来源状态
     */
    private String source;
    
    /**
     * 目标状态
     */
    private String target;
    
    /**
     * 动作
     */
    private Action action;
    
    /**
     * 拦截列表
     */
    private List<StateMachineInterceptor> interceptorList;
    
    
    /**
     * 执行状态转换
     *
     * @param stateContext 状态上下文
     * @return {@link Response}
     */
    public Response transit(StateMachineContext stateContext) {
        try {
            Response preResponse = action.preExecute(stateContext);
            if (preResponse.isSuccess()) {
                Response response = action.execute(stateContext);
                action.postExecute(stateContext);
                return response;
            }
            return preResponse;
        } finally {
            action.afterCompletion(stateContext);
        }
    }
    
    
}
